import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
import tensorflow as tf


# ------------ 会话的创建 -------------
# a = tf.constant(1)
# b = tf.constant(2)
#
# c = tf.add(a, b)

# # 方法一：
# # 开启会话
# sess = tf.compat.v1.Session()
# ret = sess.run(c)
# print("ret:", ret)
#
# # 会话结束，关闭会话
# sess.close()

# # 方法二
# with tf.compat.v1.Session() as sess:
#     ret = sess.run(c)
#     print("ret: ", ret)

# ---------------- 运行会话并打印设备信息 -------------
# with tf.Session(config=tf.ConfigProto(allow_soft_placement=True,
#                                       log_device_placement=True)) as sess:
#     print(sess.run(a))  # Const: (Const): /job:localhost/replica:0/task:0/device:CPU:0
#     print(sess.run(b))  # Const_1: (Const): /job:localhost/replica:0/task:0/device:CPU:0
#     print(sess.run(c))  # Add: (Add): /job:localhost/replica:0/task:0/device:CPU:0
#     print(c.eval())  # 和run()等价，必须在Session()的上下文环境中使用

# --------------- placeholder ----------------------
# tf.placeholder是占位的意思
plt_a = tf.placeholder(tf.float32)
plt_b = tf.placeholder(tf.float32)
plt_1 = tf.constant(1)
plt_2 = tf.constant(2)

plt_c = tf.add(plt_a, plt_b)
plt_3 = tf.add(plt_1, plt_2)

with tf.compat.v1.Session() as sess:
    # feed_dict是填充占位的变量，或改变已经赋予OP操作的变量，注意类型要一样，否则会报错
    print(sess.run(plt_c, feed_dict={plt_a: 1.0, plt_b: 2.0}))  # 3.0
    print(sess.run(plt_3, feed_dict={plt_1: 2, plt_2: 3}))  # 5
    print(plt_2.eval())  # 2
    print(plt_3.eval())  # 3
